package com.ruiyangwang.ListenBook.servlet.track;

import com.ruiyangwang.ListenBook.dataObject.UserDo;
import com.ruiyangwang.ListenBook.repository.TrackRepo;
import com.ruiyangwang.ListenBook.util.Log;
import com.ruiyangwang.ListenBook.viewObject.UserV0;
import lombok.SneakyThrows;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

/**
 * @author syzygy
 * @date 2022/07/11 19:30
 **/
@WebServlet("/studio/track/upload.do")
@MultipartConfig
public class UploadDoServlet extends HttpServlet {
    private final TrackRepo trackRepo = new TrackRepo();
    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //验证用户是否登录，若未登录，提示用户进行登录
        UserV0 userV0 = null;
        HttpSession session =req.getSession(false);
        if(session != null){
            userV0 = (UserV0) session.getAttribute("currentUser");
        }
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/plain");
        PrintWriter writer =resp.getWriter();
        if(userV0 == null){
            writer.println("用户未登录，需要登录");
            return;
        }
        //用户已登录
        writer.println("登录用户名:" + userV0.username);
        //从请求中获取信息
        req.setCharacterEncoding("utf-8");
        String title = req.getParameter("title");
        Log.println("获取到的 title 是 " + title);
        Part track =req.getPart("track");
        String type = track.getContentType();
        Log.println("获取到的 type 是 " + type);

        // 可以从这个 InputStream 中读取出来音频内容
        InputStream contentInputStream =track.getInputStream();
        trackRepo.insert(userV0.uid,title,type,contentInputStream);
        Log.println("上传成功");

        //相应插入成功
        writer.println("上传成功");


    }
}